<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="移动端开发经常会遇到图片压缩的问题，场景有更新头像，发帖等。今天我们就了解一下">
<meta name="keywords" content="机器学习 爬虫 iOS">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS-图片压缩">
<meta property="og:url" content="https://rencheng.cc/2019/10/01/ios/general/图片压缩技术/index.html">
<meta property="og:site_name" content="PHOENIX&#39;s Blog">
<meta property="og:description" content="移动端开发经常会遇到图片压缩的问题，场景有更新头像，发帖等。今天我们就了解一下">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://object.renchengqi.com/blog/f7jhz.jpg-thumb100">
<meta property="og:image" content="https://object.renchengqi.com/blog/lmr0l.jpg-thumb100">
<meta property="og:updated_time" content="2019-10-01T08:38:25.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="iOS-图片压缩">
<meta name="twitter:description" content="移动端开发经常会遇到图片压缩的问题，场景有更新头像，发帖等。今天我们就了解一下">
<meta name="twitter:image" content="https://object.renchengqi.com/blog/f7jhz.jpg-thumb100">



  <link rel="alternate" href="/atom.xml" title="PHOENIX's Blog" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://rencheng.cc/2019/10/01/ios/general/图片压缩技术/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>iOS-图片压缩 | PHOENIX's Blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">PHOENIX's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Enjoy the journey of life</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://rencheng.cc/2019/10/01/ios/general/图片压缩技术/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="任成">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="PHOENIX's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">iOS-图片压缩

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-10-01 16:38:25" itemprop="dateCreated datePublished" datetime="2019-10-01T16:38:25+08:00">2019-10-01</time>
            

            
          </span>

          

          
            
            
          

          
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                <span title="本文字数">3.3k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>移动端开发经常会遇到图片压缩的问题，场景有更新头像，发帖等。今天我们就了解一下</p>
<a id="more"></a>
<h2 id="图片格式基础"><a href="#图片格式基础" class="headerlink" title="图片格式基础"></a>图片格式基础</h2><ul>
<li>点阵图：也叫位图。用像素为单位，像素保存颜色信息，排列像素实现显示。</li>
<li>矢量图：记录元素形状和颜色的算法，显示时展示算法运算的结果。</li>
</ul>
<h2 id="颜色"><a href="#颜色" class="headerlink" title="颜色"></a>颜色</h2><p>表示颜色时，有两种形式，一种为索引色（Index Color），一种为直接色（Direct Color）</p>
<ul>
<li>索引色：用一个数字索引代表一种颜色，在图像信息中存储数字到颜色的映射关系表（调色盘 Palette）。每个像素保存该像素颜色对应的数字索引。一般调色盘只能存储有限种类的颜色，通常为 256 种。所以每个像素的数字占用 1 字节（8 bit）大小。</li>
<li>直接色：用四个数字来代表一种颜色，数字分别对应颜色中红色，绿色，蓝色，透明度（RGBA）。每个像素保存这四个纬度的信息来代表该像素的颜色。根据色彩深度（每个像素存储颜色信息的 bit 数不同），最多可以支持的颜色种类也不同，常见的有 8 位（R3+G3+B2）、16 位（R5+G6+B5）、24 位（R8+G8+B8）、32 位（A8+R8+G8+B8）。所以每个像素占用 1~4 字节大小。</li>
</ul>
<h2 id="移动端常用图片格式"><a href="#移动端常用图片格式" class="headerlink" title="移动端常用图片格式"></a>移动端常用图片格式</h2><p>图片格式中一般分为静态图和动态图</p>
<h3 id="静态图"><a href="#静态图" class="headerlink" title="静态图"></a>静态图</h3><ul>
<li><p>JPG：是支持 JPEG（ 一种有损压缩方法）标准中最常用的图片格式。采用点阵图。常见的是使用 24 位的颜色深度的直接色（不支持透明）。</p>
</li>
<li><p>PNG：是支持无损压缩的图片格式。采用点阵图。PNG 有 5 种颜色选项：索引色、灰度、灰度透明、真彩色（24 位直接色）、真彩色透明（32 位直接色）。</p>
</li>
<li><p>WebP：是同时支持有损压缩和无所压缩的的图片格式。采用点阵图。支持 32 位直接色。移动端支持情况如下：</p>
</li>
</ul>
<div class="table-container">
<table>
<thead>
<tr>
<th>系统</th>
<th>原生</th>
<th>WebView</th>
<th>浏览器</th>
</tr>
</thead>
<tbody>
<tr>
<td>iOS</td>
<td>第三方库支持</td>
<td>不支持</td>
<td>支持</td>
</tr>
<tr>
<td>Android</td>
<td>4.3后支持完整功能</td>
<td>支持</td>
<td>支持</td>
</tr>
</tbody>
</table>
</div>
<h3 id="动态图"><a href="#动态图" class="headerlink" title="动态图"></a>动态图</h3><ul>
<li>GIF：是支持无损压缩的图片格式。采用点阵图。使用索引色，并有 1 位透明度通道（透明与否）。</li>
<li>APNG：基于 PNG 格式扩展的格式，加入动态图支持。采用点阵图。使用 32 位直接色。但没有被官方 PNG 接纳。移动端支持情况如下：</li>
</ul>
<div class="table-container">
<table>
<thead>
<tr>
<th>系统</th>
<th>原生</th>
<th>WebView</th>
<th>浏览器</th>
</tr>
</thead>
<tbody>
<tr>
<td>iOS</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
</tr>
<tr>
<td>Android</td>
<td>第三方库支持</td>
<td>不支持</td>
<td>不支持</td>
</tr>
</tbody>
</table>
</div>
<ul>
<li>Animated Webp：Webp 的动图形式，实际上是文件中打包了多个单帧 Webp，在 libwebp 0.4 后开始支持。移动端支持情况如下：</li>
</ul>
<div class="table-container">
<table>
<thead>
<tr>
<th>系统</th>
<th>原生</th>
<th>WebView</th>
<th>浏览器</th>
</tr>
</thead>
<tbody>
<tr>
<td>iOS</td>
<td>第三方库支持</td>
<td>不支持</td>
<td>不支持</td>
</tr>
<tr>
<td>Android</td>
<td>第三方库支持</td>
<td>不支持</td>
<td>不支持</td>
</tr>
</tbody>
</table>
</div>
<p>而由于一般项目需要兼容三端（iOS、Android、Web 的关系），最简单就是支持 JPG、PNG、GIF 这三种通用的格式。所以本文暂不讨论其余图片格式的压缩。</p>
<h2 id="移动端系统图片处理架构"><a href="#移动端系统图片处理架构" class="headerlink" title="移动端系统图片处理架构"></a>移动端系统图片处理架构</h2><p>根据我的了解，画了一下 iOS&amp;Android 图片处理架构。iOS 这边，也是可以直接调用底层一点的框架的。</p>
<p><img src="https://object.renchengqi.com/blog/f7jhz.jpg-thumb100" alt></p>
<h2 id="iOS-的-ImageIO"><a href="#iOS-的-ImageIO" class="headerlink" title="iOS 的 ImageIO"></a>iOS 的 ImageIO</h2><p>本文 iOS 端处理图片主要用 ImageIO 框架，使用的原因主要是静态图动态图 API 调用保持一致，且不会因为 UIImage 转换时会丢失一部分数据的信息。</p>
<p>ImageIO 主要提供了图片编解码功能，封装了一套 C 语言接口。在 Swift 中不需要对 C 对象进行内存管理，会比 Objective-C 中使用方便不少，但 api 结果返回都是 Optional（实际上非空），需要用 <code>guard/if</code>，或者 !进行转换。</p>
<h3 id="解码"><a href="#解码" class="headerlink" title="解码"></a>解码</h3><p><strong>1. 创建 CGImageSource</strong><br><code>CGImageSource</code> 相当于 ImageIO 数据来源的抽象类。通用的使用方式 <code>CGImageSourceCreateWithDataProvider:</code> 需要提供一个 DataProvider，可以指定文件、URL、Data 等输入。也有通过传入 CFData 来进行创建的便捷方法 <code>CGImageSourceCreateWithData:</code>。方法的第二个参数 options 传入一个字典进行配置。根据 Apple 在 WWDC 2018 上的 <span class="exturl" data-url="aHR0cHM6Ly9kZXZlbG9wZXIuYXBwbGUuY29tL3ZpZGVvcy9wbGF5L3d3ZGMyMDE4LzIxOS8=" title="https://developer.apple.com/videos/play/wwdc2018/219/">Image and Graphics Best Practices<i class="fa fa-external-link"></i></span> 上的例子，当不需要解码仅需要创建 <code>CGImageSource</code> 的时候，应该将 <code>kCGImageSourceShouldCache</code> 设为 false。</p>
<p><img src="https://object.renchengqi.com/blog/lmr0l.jpg-thumb100" alt></p>
<p><strong>2. 解码得到 CGImage</strong><br>用 <code>CGImageSourceCreateImageAtIndex:</code> 或者 <code>CGImageSourceCreateThumbnailAtIndex:</code> 来获取生成的 <code>CGImage</code>，这里参数的 Index 就是第几帧图片，静态图传入 0 即可。</p>
<h3 id="编码"><a href="#编码" class="headerlink" title="编码"></a>编码</h3><p><strong>1. 创建 CGImageDestination</strong><br><code>CGImageDestination</code> 相当于<code>ImageIO</code>数据输出的抽象类。通用的使用方式 <code>CGImageDestinationCreateWithDataConsumer:</code>需要提供一个 <code>DataConsumer</code>，可以置顶 URL、Data 等输入。也有通过传入 CFData 来进行创建的便捷方法 <code>CGImageDestinationCreateWithData:</code>，输出会写入到传入的<code>Data</code>中。方法还需要提供图片类型，图片帧数。</p>
<p><strong>2. 添加 CGImage</strong><br>添加 <code>CGImage</code> 使用<code>CGImageDestinationAddImage:</code>方法，动图的话，按顺序多次调用就行了。</p>
<p>而且还有一个特别的 <code>CGImageDestinationAddImageFromSource:</code> 方法，添加的其实是一个<code>CGImageSource</code>，有什么用呢，通过<code>options</code> 参数，达到改变图像设置的作用。比如改变 JPG 的压缩参数，用上这个功能后，就不需要转换成更顶层的对象（比如 <code>UIImage</code>），减少了转换时的编解码的损耗，达到性能更优的目的。</p>
<p><strong>3. 进行编码</strong><br>调用 <code>CGImageDestinationFinalize:</code>，表示开始编码，完成后会返回一个<code>Bool</code>值，并将数据写入 <code>CGImageDestination</code> 提供的 DataConsumer 中。</p>
<h2 id="压缩思路分析"><a href="#压缩思路分析" class="headerlink" title="压缩思路分析"></a>压缩思路分析</h2><p>位图占用的空间大小，其实就是像素数量 x 单像素占用空间 x 帧数。所以减小图片空间大小，其实就从这三个方向下手。其中单像素占用空间，在直接色的情况下，主要和色彩深度相关。在实际项目中，改变色彩深度会导致图片颜色和原图没有保持完全一致，笔者并不建议对色彩深度进行更改。而像素数量就是平时非常常用的图片分辨率缩放。除此之外，JPG 格式还有特有的通过指定压缩系数来进行有损压缩。</p>
<p>JPG：压缩系数 + 分辨率缩放 + 色彩深度降低<br>PNG： 分辨率缩放 + 降低色彩深度<br>GIF：减少帧数 + 每帧分辨率缩放 + 减小调色盘</p>
<p><span class="exturl" data-url="aHR0cHM6Ly9uZW1vY2R6LmdpdGh1Yi5pby9wb3N0LyVFNiVCNSU4NSVFOCVCMCU4OCVFNyVBNyVCQiVFNSU4QSVBOCVFNyVBQiVBRiVFNSU5QiVCRSVFNyU4OSU4NyVFNSU4RSU4QiVFNyVCQyVBOS8jJUU1JTlCJUJFJUU3JTg5JTg3JUU2JUEwJUJDJUU1JUJDJThGJUU1JTlGJUJBJUU3JUExJTgw" title="https://nemocdz.github.io/post/%E6%B5%85%E8%B0%88%E7%A7%BB%E5%8A%A8%E7%AB%AF%E5%9B%BE%E7%89%87%E5%8E%8B%E7%BC%A9/#%E5%9B%BE%E7%89%87%E6%A0%BC%E5%BC%8F%E5%9F%BA%E7%A1%80">https://nemocdz.github.io/post/%E6%B5%85%E8%B0%88%E7%A7%BB%E5%8A%A8%E7%AB%AF%E5%9B%BE%E7%89%87%E5%8E%8B%E7%BC%A9/#%E5%9B%BE%E7%89%87%E6%A0%BC%E5%BC%8F%E5%9F%BA%E7%A1%80<i class="fa fa-external-link"></i></span></p>
<h2 id="目的"><a href="#目的" class="headerlink" title="目的"></a>目的</h2><p>减少图片占用内存空间</p>
<h2 id="质量压缩"><a href="#质量压缩" class="headerlink" title="质量压缩"></a>质量压缩</h2><p>图片的质量压缩 降低图片质量（大小）。<br><strong>原理</strong><br>通过算法扣掉（同化）了 图片中的一些某个点附近相近的像素，达到降低质量 减少 文件大小的目的。</p>
<blockquote>
<p>他其实只能 实现对 file 的影响，对加载这个图片出来的bitmap 内存是无法节省的 ，还是那么大。 因为 bitmap 在内存中的大小是按照 像素 计算的 ，也就是width * height ，对于质量压缩，并不会改变图片的真实的像素（像素大小不会变）。</p>
</blockquote>
<h2 id="尺寸压缩"><a href="#尺寸压缩" class="headerlink" title="尺寸压缩"></a>尺寸压缩</h2><p>就是按照一定的倍数对图片减少单位尺寸的像素值。<br><strong>原理</strong><br>通过减少单位尺寸的像素值，真正意义上的降低像素值。</p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/09/27/search/微信分享卡片点击跳转App/" rel="next" title="微信分享卡片点击跳转App">
                <i class="fa fa-chevron-left"></i> 微信分享卡片点击跳转App
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/10/09/docker/Docker运行Nginx/" rel="prev" title="Docker运行Nginx">
                Docker运行Nginx <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.JPG" alt="任成">
            
              <p class="site-author-name" itemprop="name">任成</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0NvZGVyQ3VydmU=" title="GitHub &rarr; https://github.com/CoderCurve"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOnJlbmNoZW5nMTFAaWNsb3VkLmNvbQ==" title="E-Mail &rarr; mailto:rencheng11@icloud.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#图片格式基础"><span class="nav-number">1.</span> <span class="nav-text">图片格式基础</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#颜色"><span class="nav-number">2.</span> <span class="nav-text">颜色</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#移动端常用图片格式"><span class="nav-number">3.</span> <span class="nav-text">移动端常用图片格式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#静态图"><span class="nav-number">3.1.</span> <span class="nav-text">静态图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#动态图"><span class="nav-number">3.2.</span> <span class="nav-text">动态图</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#移动端系统图片处理架构"><span class="nav-number">4.</span> <span class="nav-text">移动端系统图片处理架构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#iOS-的-ImageIO"><span class="nav-number">5.</span> <span class="nav-text">iOS 的 ImageIO</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#解码"><span class="nav-number">5.1.</span> <span class="nav-text">解码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编码"><span class="nav-number">5.2.</span> <span class="nav-text">编码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#压缩思路分析"><span class="nav-number">6.</span> <span class="nav-text">压缩思路分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#目的"><span class="nav-number">7.</span> <span class="nav-text">目的</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#质量压缩"><span class="nav-number">8.</span> <span class="nav-text">质量压缩</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#尺寸压缩"><span class="nav-number">9.</span> <span class="nav-text">尺寸压缩</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备18001214号 </span>&copy; 2014 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">任成</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
    <span title="站点总字数">277k</span>
  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'forest',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  

  

  

  

  

  

  

  

  

</body>
</html>
